<?php

namespace app\api\controller;

use app\admin\model\UserMill;
use app\common\model\CashLog;
use app\common\model\MyMill;
use app\common\controller\Api;
use think\Db;
use think\Exception;


/**
 * 矿机接口
 */
class Mill extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['mill_list'];
    protected $noNeedRight = ['*'];


    /*
     * 矿机列表
     * */
    public function mill_list()
    {
        //$user = $this->auth->getUser();

        $page = $this->request->request('page');
        $list_rows = $this->request->request('list_rows');
        $page = $page ? $page : 1;
        $list_rows = $list_rows ? $list_rows : config('site.list_rows');

        $mill = new \app\common\model\Mill();

        $where = ['status'  =>  config('MillStatus.enable')];

        $mill_list = $mill
            ->where($where)
            ->page($page,$list_rows)
            ->select();

        $this->success('矿机列表',$mill_list);
    }

    /*
     * 购买矿机
     * */
    public function buy_mill()
    {

        $result = $this->validate($this->request->request(),'Mill.buy_mill');
        if ($result !== true)$this->error($result);

        $user = $this->auth->getUser();

        $pay_password = $this->request->request('pay_password');
        $mill_id = $this->request->request('mill_id');

        //  判断支付密码
        if ($user->pay_password !== $this->auth->getEncryptPassword($pay_password,$user->salt))
        {
            $this->error('支付密码错误');
        }

        //  获取矿机信息
        $mill = \app\common\model\Mill::get($mill_id);

        if (!$mill || $mill->status == config('MillStatus.disable'))
        {
            $this->error('矿机不存在或已下架');
        }

        if ($mill->realname == 1 && !$user->is_realname)
        {
            $this->error('需要先实名认证才能购买');
        }

        if ($mill->price > $user->cash_money)
        {
            $this->error('余额不足，请先充值');
        }

        //  添加用户矿机信息数据
        $time = time();
        //  矿机列表数据
        $user_mill_data = [
            'mill_id'   =>  $mill_id,
            'user_id'   =>  $user->id,
            'mill_name' =>  $mill->mill_name,
            'earnings'  =>  $mill->earnings,
            'period'    =>  $mill->period,
            'status'    =>  config('MillStatus.disable'),
            'buy_time'  =>  $time
        ];
        //  用户资金变动
        $user_data = [
            'cash_money'    =>  $user->cash_money - $mill->price
        ];
        //  用户资金变动记录
        $cash_log_data = [
            'user_id'   =>  $user->id,
            'value'     =>  $mill->price,
            'detail'    =>  '购买矿机',
            'type'      =>  config('CashType.ExchangeOut'),
            'pay_manner'=>  config('PayManner.cash'),
            'time'      =>  $time,
            'status'    =>  config('PayStatus.Finished'),
            'order_id'  =>  generate_order_id($user->id)
        ];


        $user_mill = new MyMill();
        $cash_log = new CashLog();

        //  事务提交
        Db::startTrans();
        try{
            $user_mill->data($user_mill_data)->save();
            $cash_log->data($cash_log_data)->save();
            $user->data($user_data)->save();
            Db::commit();
        }
        catch (\Exception $ex)
        {
            Db::rollback();
            $this->error($ex);
        }
        $this->success('矿机购买成功',$user_mill_data);
    }



    /*
     * 我的矿机
     * */
    public function my_mill_list()
    {
        $user = $this->auth->getUser();

        $page = $this->request->request('page');
        $list_rows = $this->request->request('list_rows');
        $page = $page ? $page : 1;
        $list_rows = $list_rows ? $list_rows : config('site.list_rows');

        $my_mill = new UserMill();

        $my_mill_list = $my_mill
            ->where('user_id','=',$user->id)
            ->page($page,$list_rows)
            ->order('buy_time','desc')
            ->select();
        //  处理数据
        $result = [];
        foreach ($my_mill_list as $item)
        {
            $item_data = $item->getData();
            switch ($item_data['status'])
            {// 智能判断时间和状态
                case config('MillStatus.disable'):
                    //  未启用状态
                    $item_data['status'] = '启用';
                    $item_data['time'] = date('Y-m-d H:i:s',$item['buy_time']);
                    break;
                case config('MillStatus.enable'):
                    $item_data['status'] = '运行中';
                    $item_data['time'] = date('Y-m-d H:i:s',$item['start_time']);
                    break;
                case config('MillStatus.close'):
                    $item_data['status'] = '已结束';
                    $item_data['time'] = date('Y-m-d H:i:s',$item['end_time']);
                    break;
            }
            unset($item_data['mill_id'],$item_data['user_id'],$item_data['data']);
            $result[] = $item_data;
        }

        $this->success('我的矿机列表',$result);

    }

    /*
     * 矿机状态启用
     * */

    public function mill_enable()
    {
        //  判断我的矿机id
        $result = $this->validate($this->request->request(),'Mill.mill_enable');
        if ($result !== true) $this->error($result);

        $mill_id = $this->request->request('my_mill_id');

        $mill = UserMill::get($mill_id);

        //  检测矿机是否存在
        if (!$mill)
        {
            $this->error('所选矿机不存在');
        }

        if ($mill->status == config('MillStatus.enable'))
        {
            $this->error('矿机已启用');
        }


        $mill->data([
            'status'    =>  config('MillStatus.enable'),
            'start_time'=>  time(),
            'buy_time'  =>  $mill->buy_time,
            'end_time'  =>  $mill->end_time,
        ]);

        if ($mill->allowField(true)->save() != false)
        {
            $res = [
                'status'=>'运行中',
                'time'  =>  date('Y-m-d H:i:s',$mill->start_time)
            ];
            $this->success('矿机启用成功',$res);
        }else
        {
            $this->error('矿机启用失败',['status'=>'启用','time'=>$mill->buy_time]);
        }
    }

}
